package com.sansui.blog.service.impl;

import com.sansui.blog.dao.SysInfoDao;
import com.sansui.blog.dao.ThemesDao;
import com.sansui.blog.pojo.Theme;
import com.sansui.blog.service.ThemesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @name: ThemesServiceImpl
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-08-09 23:06
 **/
@Service
public class ThemesServiceImpl implements ThemesService{

    @Autowired
    private ThemesDao themesDao;

    @Autowired
    private SysInfoDao sysInfoDao;

    @Override
    public Map<String, Object> getThemesList() {
        Map<String,Object> data = new HashMap<>(16);
        try{
            List<Theme> themes = themesDao.getThemesList();
            data.put("code",0);
            data.put("msg","查询成功！");
            data.put("count",themes.size());
            data.put("data",themes);
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",400);
            data.put("msg","查询失败！");
        }
        return data;
    }


    @Transactional
    @Override
    public Map<String, Object> updateThemes(Long themeId) {
        Map<String,Object> data = new HashMap<>(16);
        try{
            Theme theme = themesDao.getThemeByid(themeId);
            if(theme == null){
                data.put("code",401);
                data.put("msg","修改失败,主题不存在！");
                return data;
            }
            if(theme.getEnable()){
                data.put("code",402);
                data.put("msg","修改失败,正在使用该主题！");
                return data;
            }
            //清空在用主题
            boolean deleteThemesEnable = themesDao.deleteThemesEnable();
            //修改选中主题
            boolean updateNum = themesDao.updateThemes(themeId);
            //更新系统信息使用主题名称
            boolean updateSysInfo = sysInfoDao.updateThemeName(theme.getName());

            if(!deleteThemesEnable || !updateNum || !updateSysInfo){
                data.put("code",402);
                data.put("msg","修改失败！");
                return data;
            }
            data.put("code",200);
            data.put("msg","修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",400);
            data.put("msg","修改失败！");
        }
        return data;
    }

}
